package com.wajahatkarim3.rdbexplorer.demo.slice;

import com.wajahatkarim3.rdbexplorer.demo.ResourceTable;
import com.wajahatkarim3.rdbexplorer.slice.RdbExplorerAbilitySlice;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.*;
import ohos.agp.window.dialog.ToastDialog;
import ohos.agp.window.service.WindowManager;
import ohos.data.DatabaseHelper;
import ohos.data.orm.OrmContext;
import ohos.data.orm.OrmPredicates;
import ohos.data.rdb.RdbStore;
import ohos.data.rdb.StoreConfig;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
public class MainAbilitySlice extends AbilitySlice implements Serializable {

    DatabaseHelper helper;
    List<Todo> list = new ArrayList<>();
    TodoItemProvider provider;
    StoreConfig config;
    OrmContext context;
    static final String dbNameAlias = "TodoStore";
    static final String dbName = "TodoStore.db";
    RdbStore rdbStore;

    static final HiLogLabel LABEL = new HiLogLabel(HiLog.LOG_APP, 0x00201, "HOSDBEXPLORER_TAG");

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        initView();
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    private void initView() {
        if (context == null) {
            config = StoreConfig.newDefaultConfig(dbName);
            helper = new DatabaseHelper(MainAbilitySlice.this);
            context = helper.getOrmContext(dbNameAlias, dbName, TodoStore.class);
            rdbStore = helper.getRdbStore(config, 1, null);
        }
        RdbExplorerAbilitySlice.setRdbStore(rdbStore);
        loadAllTodos();
        ListContainer recyclerTodos = (ListContainer) findComponentById(ResourceTable.Id_recyclerTodos);
        provider = new TodoItemProvider(this,  list);

        provider.setItemClickedListener(new TodoItemProvider.ItemClickedListener() {
            @Override
            public void onChecked(int i) {
                if (i >= 0) {
                    context.beginTransaction();
                    OrmPredicates query = context.where(Todo.class);
                    query.equalTo("id", list.get(i).getId());
                    context.delete(query);
                    context.flush();
                    context.commit();
                    loadAllTodos();
                    provider.notifyDataChanged();
                }
            }
        });
        recyclerTodos.setItemProvider(provider);
        Image imgAdd = (Image) findComponentById(ResourceTable.Id_imgAdd);
        TextField txtTodoTask = (TextField) findComponentById(ResourceTable.Id_txtTodoTask);

        txtTodoTask.setClickedListener(component -> {
            getWindow().setInputPanelDisplayType(WindowManager.LayoutConfig.INPUT_ADJUST_PAN);
        });

        Text showDatabase = (Text) findComponentById(ResourceTable.Id_database_show);
        if (imgAdd != null) {
            imgAdd.setClickedListener(component -> {
                if (txtTodoTask.getText().isEmpty()) {
                    new ToastDialog(this).setText("Todo title cannot be empty!").setDuration(2000).show();
                } else {
                    context.beginTransaction();
                    context.insert(new Todo(null, txtTodoTask.getText(), false));
                    context.flush();
                    context.commit();
                    loadAllTodos();
                    provider.notifyDataChanged();
                    txtTodoTask.setText("");
                }
            });
        }

        if (showDatabase != null) {
            showDatabase.setClickedListener(new Component.ClickedListener() {
                @Override
                public void onClick(Component component) {
                    Intent intent = new Intent();

                    Operation operation = new Intent.OperationBuilder()
                            .withDeviceId("")
                            .withBundleName("com.wajahatkarim3.rdbexplorer.demo")
                            .withAbilityName("com.wajahatkarim3.rdbexplorer.RdbExplorerAbility")
                            .build();

                    intent.setOperation(operation);
                    startAbility(intent);
                }
            });
        }
    }

    private void loadAllTodos() {
        list.clear();
        OrmPredicates query = context.where(Todo.class);
        list.addAll(context.query(query));
    }

}
